package com.neuedu.controller;


import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
public class DownloadController {


    /**
     * 3000
     *
     * 1024  1024 (2048)   954
     *
     *
     * @param path
     * @param response
     * @throws IOException
     */

    @GetMapping("/d1/{path}")
    public void download(@PathVariable String path , HttpServletResponse response) throws IOException {

        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.addHeader(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename="+path);

        InputStream is = new FileInputStream(new File(BootConstants.UPLOAD_DIR,path));
        OutputStream os = response.getOutputStream();
        int len = -1;
        byte[] bytes = new byte[1024];
        while (   (len = is.read(bytes)) != -1){
            os.write(bytes,0,len);
        }
        os.close();
        is.close();
    }

    @GetMapping("/d2/{path}")
    public ResponseEntity download2(@PathVariable String path ) throws IOException {

        return ResponseEntity.ok().
                header(HttpHeaders.CONTENT_TYPE,"application/octet-stream").
                header(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename="+path).
                body(new FileSystemResource(new File(BootConstants.UPLOAD_DIR,path)));
    }


}
